package org.tony.spider.tieba;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.tony.spider.common.GetRequestor;

public class TiebaDetailQueryRunner
    implements Runnable
{
  private String chapterUrl;
  private String savePath;
  private File   file;

  public TiebaDetailQueryRunner(String chapterUrl, String savePath)
  {
    this.chapterUrl = chapterUrl;
    this.savePath = savePath;
    file = new File(this.savePath);
    if (!file.exists())
    {
      file.getParentFile().mkdirs();
      try
      {
        file.createNewFile();
      }
      catch (IOException e)
      {
        System.err.println(String.format("file %s create failed ", savePath));
      }
    }
  }

  public void run()
  {
    GetRequestor getReq = new GetRequestor();
    String content = getReq.startGet(chapterUrl);
    Document doc = Jsoup.parse(content);
    Elements eles = doc.select("div.readpage_leftntxt");
    if (eles.size() == 1)
    {
      Element el = eles.first();
      el.select("p").remove();
      el.select("div").remove();
      Iterator<Node> nodes = el.childNodes().iterator();
      OutputStream fos = null;
      try
      {
        fos = new FileOutputStream(file);
        while (nodes.hasNext())
        {
          Node node = nodes.next();
          if (node instanceof TextNode)
          {
            fos.write(((TextNode)node).text().getBytes("UTF-8"));
            fos.write("\n".getBytes("UTF-8"));
          }
        }

      }
      catch (Exception e)
      {
        try
        {
          fos.flush();
          fos.close();
        }
        catch (IOException e1)
        {
          System.err.println(e1);
        }
        System.err.println(e);
      }

    }
  }
}
